package cn.zyjblogs.starter.mybatisplus.config;

import com.alibaba.fastjson2.JSON;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.springframework.util.CollectionUtils;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;

public class MapToStringHandler<K, V> extends BaseTypeHandler<Map<K, V>> {


    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, Map map, JdbcType jdbcType) throws SQLException {
        if (!CollectionUtils.isEmpty(map)) {
            preparedStatement.setString(i, JSON.toJSONString(map));
        } else {
            preparedStatement.setString(i, null);
        }
    }

    @Override
    public Map getNullableResult(ResultSet resultSet, String s) throws SQLException {
        String result = resultSet.getString(s);
        return result == null ? null : JSON.parseObject(result, Map.class);
    }

    @Override
    public Map getNullableResult(ResultSet resultSet, int i) throws SQLException {
        String result = resultSet.getString(i);
        return result == null ? null : JSON.parseObject(result, Map.class);
    }

    @Override
    public Map getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        String result = callableStatement.getString(i);
        return result == null ? null : JSON.parseObject(result, Map.class);
    }
}
